﻿using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Web.Mvc.Binders;
using KingsSharp.Web.UI;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace CRM.Admin.Areas.Sys.Controllers
{
    public class AuthorizationController : Controller
    {
        public IRoleService RoleService { get; set; }

        public IAuthorizationService AuthorizationService { get; set; }

        public ActionResult AuthorizationIndex()
        {
            var dtos = RoleService.ItemRole.Where(a => a.IsDeleted == false).ToList().MapToList<Role, RoleDto>();
            return View(dtos);
        }

        #region 数据功能
        public class AuthtempDto
        {
            public string RoleName { get; set; }
            public Guid RoleId { get; set; }

            public AuthorizationDto[] AuthDtos { get; set; }
        }
        public ActionResult InsertOrUpdateAuthorization([ModelBinder(typeof(JsonBinder<AuthtempDto>))] AuthtempDto authtempdto)
        {
            authtempdto.CheckNotNull("dtos");
            for (int i = 0; i < authtempdto.AuthDtos.Length; i++)
            {
                authtempdto.AuthDtos[i].Id = Guid.NewGuid();
            }
            var result = AuthorizationService.InsertOrUpdateAuthorization(authtempdto.RoleId, authtempdto.AuthDtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "角色“{0}”授权成功。".FormatWith(authtempdto.RoleName);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        [HttpPost]
        public ActionResult GetRoleAuthorization(Guid RoleId)
        {
            var authoriztions = AuthorizationService.ItemAuthorization.
                Where(a => a.RoleId == RoleId && a.IsDeleted == false)
                .Select(a => new { a.Id, a.RoleId, a.MenuNodeId, a.ActionCodes }).ToList();
            return Json(authoriztions);
        }
        [HttpPost]
        public ActionResult GetAllMenuGridData()
        {
            var catalogs = MenuItem.Instance.GetCatalogTree().ToList();

            List<AuthtreeView> ztree = catalogs.RenderTree<MenuCatalog, AuthtreeView>(
              catalogs.Where(a => a.ParentMenuCatalog == null).ToList(), (catalog, level) =>
              {
                  List<AuthtreeView> item = new List<AuthtreeView>();
                  foreach (var node in catalog.Menus)
                  {
                      string path = "";
                      foreach (var ac in node.Actions)
                      {
                          if (path != "")
                          {
                              path = path + ",";
                          }
                          path = path + ac.Code;
                      }
                      item.Add(new AuthtreeView()
                      {
                          Id = node.Id.ToString(),
                          Name = node.Name,
                          Description = node.Description,
                          ActionNode = 2,
                          ActionPath = path
                      });
                  }
                  return new AuthtreeView()
                  {
                      Id = catalog.Id.ToString(),
                      Name = catalog.Name,
                      Type = catalog.Type.ToString(),
                      children = item,
                      ActionNode = 1

                  };
              }, (catalog, sources) =>
              {
                  return sources.Where(a => a.ParentMenuCatalog != null
                      && a.ParentMenuCatalog.Id == catalog.Id).ToList();
              }, (parentNode, newNode) =>
              {
                  if (parentNode.children == null)
                  {
                      parentNode.children = new List<AuthtreeView>();
                  }
                  parentNode.children.Add(newNode);
              }
               ).ToList();

            List<AuthtreeView> ztreeall = new List<AuthtreeView>();
            typeof(SystemMenuType).Each((a, b, c) =>
            {
                if (a != SystemMenuType.AdminHideMenu.ToString())
                {
                    ztreeall.Add(new AuthtreeView()
                    {
                        Name = c,
                        Id = b,
                        children = ztree.Where(onetree => onetree.Type == b).ToList()
                    });
                }
            });
            //string jsonString = ztreeall.ToJsonString(true);//转换为小写的json

            //return Json((object)jsonString, JsonRequestBehavior.AllowGet);
            return Json(ztreeall);
        }
        #endregion
    }
    public class AuthtreeView
    {
        public AuthtreeView()
        {
            ActionNode = 0;
        }
        public string Name { get; set; }

        public string Description { get; set; }

        public string Id { get; set; }

        public string Type { get; set; }

        public short ActionNode { get; set; }

        public string ActionPath { get; set; }
        public ICollection<AuthtreeView> children { get; set; }
    }
}